/**
 * 自定义组件
 */
abstract class GameObject extends eui.Component implements eui.UIComponent {
	private isCreated: boolean = false;
	//是否将组件锚点移至中心
	public setAnchorToCenter: boolean = false;
	public background: egret.DisplayObject;
	//构造函数
	public constructor() {
		super();
		this.addEventListener(egret.Event.ADDED_TO_STAGE, this.init, this);
		this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.removeFromStage, this);
	}
	//添加到舞台后执行
	protected async init() {
		!this.isCreated && await this.firstCreate();
		this.isCreated = true;
		//将组件锚点移至中心
		if (this.setAnchorToCenter) {
			this.anchorOffsetX = this.width / 2;
			this.anchorOffsetY = this.height / 2;
		}
		this.addToStage();
	}
	protected removeFromStage() {
		this.onRemove();
	}
	//组件被移除后执行
	protected abstract onRemove();
	//第一次初始化
	protected async abstract firstCreate();
	//添加到舞台
	protected abstract addToStage();
	//从父容器移除
	public removeFromParent() {
		this.parent && this.parent.removeChild(this);
	}
	
	//更换容器
	public changeContainer(dc: egret.DisplayObjectContainer) {
		let globalPos = this.parent.localToGlobal(this.x, this.y);
		let localPos = dc.globalToLocal(globalPos.x, globalPos.y);
		this.removeFromParent();
		dc.addChild(this);
		this.x = localPos.x;
		this.y = localPos.y;
	}
}